package com.ruoyi.web.controller.api;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.constant.YouDaoKEY;
 
@RestController
@RequestMapping("/api/tts")
public class ApiTtsController {

    public static void binaryToBinaryFile(byte[] data, String outputFilePath) {
        
        try (InputStream is = new ByteArrayInputStream(data);
             FileOutputStream fos = new FileOutputStream(outputFilePath)) {
            // 复制数据从输入流到输出流
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) != -1) {
                fos.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void binaryStringToBinaryFile(String binaryString, String outputFilePath) {
        // 将二进制字符串转换为字节数组
        byte[] data = new BigInteger(binaryString, 2).toByteArray();
        
        try (InputStream is = new ByteArrayInputStream(data);
             FileOutputStream fos = new FileOutputStream(outputFilePath)) {
            // 复制数据从输入流到输出流
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) != -1) {
                fos.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	
    private static final Logger logger = LoggerFactory.getLogger(ApiTtsController.class);

    @PostMapping("/convert")
    public AjaxResult convert(
            @RequestParam("text") String text) throws IOException {
        
        Map<String, String> params = new HashMap<>();
        String salt = String.valueOf(System.currentTimeMillis());
        String signStr = YouDaoKEY.APP_KEY + text + salt + YouDaoKEY.APP_SECRET;
        String sign = getDigest(signStr);

        params.put("langType", "en");
        params.put("appKey", YouDaoKEY.APP_KEY);
        params.put("q", text);
        params.put("salt", salt);
        params.put("sign", sign);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(YouDaoKEY.YOUDAO_URL);
        
        List<NameValuePair> paramsList = new ArrayList<>();
        Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> en = it.next();
            paramsList.add(new BasicNameValuePair(en.getKey(), en.getValue()));
        }

        httpPost.setEntity(new UrlEncodedFormEntity(paramsList, "UTF-8"));
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

        try {
            Header[] contentType = httpResponse.getHeaders("Content-Type");
            logger.info("Content-Type: " + contentType[0].getValue());

            if ("audio/mp3".equals(contentType[0].getValue())) {
                HttpEntity httpEntity = httpResponse.getEntity();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                httpResponse.getEntity().writeTo(baos);
                byte[] audioData = baos.toByteArray();
                EntityUtils.consume(httpEntity);

                if (audioData != null && audioData.length > 0) {
                	
                	binaryToBinaryFile(audioData, RuoYiConfig.getVoicePath() + "/" + text + ".mp3");
                	
                    return AjaxResult.success("TTS转换成功");
                } else {
                    return AjaxResult.error("生成的音频数据为空");
                }
            } else {
                HttpEntity httpEntity = httpResponse.getEntity();
                String json = EntityUtils.toString(httpEntity, "UTF-8");
                EntityUtils.consume(httpEntity);
                logger.error("TTS conversion failed: " + json);
                return AjaxResult.error("TTS转换失败：" + json);
            }
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    logger.error("Error closing response: " + e.getMessage());
                }
            }
        }
    }

    private String getDigest(String string) {
        if (string == null) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        byte[] btInput = string.getBytes(StandardCharsets.UTF_8);
        try {
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            logger.error("Error generating digest: " + e.getMessage());
            return null;
        }
    }
    
}